/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package slideshow;

import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import javax.imageio.ImageIO;

/**
 *
 * @author Filippo
 */
public class ImageLoader {
    private ImageLoader() {}
    public static List<Picture> load(String dirname) throws IOException {
        List<Picture> pictures = new LinkedList<>();
        File dir = new File(dirname);
        if(dir.isDirectory()) {
            for(File f : dir.listFiles()) {
                if(f.isFile()) {
                    String filename = f.getName();
                    BufferedImage img = ImageIO.read(f);
                    if(img != null) { 
                        img = ImageLoader.adaptImage(img);
                        pictures.add(new Picture(filename,img));
                    }
                }
            }
        }
        return pictures;
    }
    private static BufferedImage adaptImage(BufferedImage image) {
        BufferedImage after;
        int width = image.getWidth();
        int height = image.getHeight();
        after = new BufferedImage(width,height,BufferedImage.TYPE_INT_ARGB);
        double scale = 1 / Math.max((double)width / WindowConstants.IMAGE_WIDTH,(double)height / WindowConstants.IMAGE_HEIGHT);
        if(scale > 0 && scale < 1) {
            AffineTransform at = new AffineTransform();
            at.scale(scale,scale);
            AffineTransformOp scaleOp = new AffineTransformOp(at,AffineTransformOp.TYPE_BILINEAR);
            after = new BufferedImage((int)(width * scale),(int)(height * scale),BufferedImage.TYPE_INT_ARGB);
            after = scaleOp.filter(image,after);
        }
        return after;
    }
}
